<?php
/**
 * Created by PhpStorm.
 * User: priestll
 * Date: 20-7-15
 * Time: 上午8:59
 */

namespace App\Biz;


use App\Model\StageLogModel;
use App\Model\StageModel;
use App\Model\StageUserModel;
use App\Model\SystemConfigModel;
use App\Model\UserModel;
use EasySwoole\ORM\DbManager;
use EasySwoole\RedisPool\Redis;
use priestll\easyswoole\biz\BaseBiz;

class StageBiz extends BaseBiz
{
    const RULE_NAME="GENERAL_RULE";
    /**
     * @param $user 用户信息
     * @return array
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function getStage($user)
    {
        $res=StageModel::create()
            ->alias("s")
            ->field(["s.name","s.title","s.description","s.power","FROM_UNIXTIME(beg_time,'%Y年%m月%d日') as beg_time","FROM_UNIXTIME(end_time,'%Y年%m月%d日') as end_time","count(l.id) as assist_num"])
            ->join("tv_lucky_stage_log as l","l.assist_id={$user["id"]} AND l.round=s.id","left")
            ->where(["s.id"=>$user["round"]])
            ->limit(1)
            ->get();
        return $this->success($res);
    }

    /**
     * @param $user_id
     * @return array
     */
    public function getUserStage($user_id)
    {
        $model = StageUserModel::create();
        $data = $model->getByUser($user_id);
        return $this->success($data);
    }

    /**
     * @param $user_id  用户id
     * @param $assist_id    被助力id
     * @param $round   轮数
     * @return array
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function assist($user_id, $assist_id)
    {
        $stageModel = StageModel::create();
        $stageLogModel = StageLogModel::create();
        $assist_user=UserModel::create()->field(["id","award_times","round",'nickname'])->where(["id"=>$assist_id])->limit(1)->get();
        if (!$assist_user)
        {
            return $this->success('助力成功');
        }
        $round=$assist_user->round?:1;
        $log = $stageModel
            ->alias("s")
            ->field(["l.id","s.beg_time","s.end_time","count(sl.id) as assist_num","s.power"])
            ->join("tv_lucky_stage_log as l"," l.user_id={$user_id} AND l.assist_id={$assist_id} ","left")
            ->join("tv_lucky_stage_log as sl"," sl.assist_id={$assist_id} AND sl.round=s.id ","left")
            ->where(["s.id"=>$round])
            ->limit(1)
            ->get();
        if (!$log||$log->id||($log->assist_num>=$log->power)) {
            return $this->fail('你已成功帮'.$assist_user->nickname.'助力');
        }
        $now = time();
        if ($now < $log->beg_time || $now > $log->end_time) {
            return $this->fail('不在活动期间');
        }
        $db = DbManager::getInstance();
        try {
            //开启事务
            $db->startTransaction();

            $stageLogModel->data([
                    'user_id' => $user_id,
                    'assist_id' => $assist_id,
                    'power' => 1,
                    'round' => $round,
                    'created_at' => time(),
            ])->save();
            if ($log->power==($log->assist_num+1))
            {
                $assist_user->award_times++;
                if (!$assist_user->update())
                {
                    throw new \Exception("SAVE AWARD_TIMES FALSE");
                }
            }

        } catch (\Throwable  $e) {
            //回滚事务
            $db->rollback();

            return $this->success($e->getMessage());
        } finally {
            //提交事务
            $db->commit();
            return $this->fail('你已成功帮'.$assist_user->nickname.'助力');
        }
    }

    public function rule()
    {
        $redis = Redis::defer(self::DEF_REDIS);
        if (!$redis->exists(self::RULE_NAME))
        {
            $rule=SystemConfigModel::create()->where(["name"=>self::RULE_NAME])->limit(1)->scalar("value");
            if (!$rule)
            {
                $rule=" 春风吹绿大地，爱心染红三月，传承雷锋精神。嘉荣举办的\"爱心超市\"活动于2020年8月1日上午在星河中心广场拉开帷幕。 ";
            }
            $redis->set(self::RULE_NAME,$rule,60*60*3);
        }
        else
        {
            $rule=$redis->get(self::RULE_NAME);
        }
        return $this->success(["rule"=>$rule]);
    }


}